<template>
    <div style="display: grid;place-items: center;margin-top: 30px;">
        <div>
            <el-input v-model="title" placeholder="请输入标题 建议30字以内" maxlength="40"
                style="width: 960px;;font-size:larger; font-weight: bold;color: red;" />
            <el-row>
                <el-upload v-model:file-list="fileList" class="upload-demo"
                    action="http://124.221.73.180:3001/upload/photo/" multiple :on-preview="handlePreview"
                    :headers="headersObj" :on-remove="handleRemove" :before-remove="clear" :limit="3"
                    :on-exceed="handleExceed" list-type="picture" :on-success="handleSuccess" :http-request="uploadFile"
                    style="margin-top: 10px;position: relative;">
                    <el-button type="primary">上传封面图片</el-button>
                </el-upload>
                <el-select v-model="tag" class="m-2" placeholder="Select"
                    style="margin-top: 10px;position: absolute;left: 130px;" clearable>
                    <el-option v-for="item in tagList" :key="item" :label="item" :value="item" />
                </el-select>
                <el-row v-if="tag == '红色景点'" style="margin-top: 10px;position: absolute;left: 358px;width: 700px;">
                    <el-select v-model="cityChoose" class="m-2" placeholder="Select" @change="handleChange" clearable
                        style="margin-right: 10px;">
                        <el-option v-for="item in city" :key="item" :label="item" :value="item" />
                    </el-select>
                    <el-select v-model="countyChoose" class="m-2" placeholder="Select" v-if="check" clearable>
                        <el-option v-for="item in county" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-row>
            </el-row>
        </div>
        <editorComponents @commit="refeshContent"></editorComponents>
        <el-button type="primary" style="width: 10%;margin:20px 0px;"
            @click="dialogVisible = true, needContent = true">提交文章</el-button>
        <!--  -->
    </div>
    <el-dialog v-model="dialogVisible" title="Tips" width="30%" :before-close="handleClose">
        <span>确定提交吗</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false, handleCommit()">
                    确定
                </el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import editorComponents from '@/components/global/editor.vue';
import { ElLoading, ElMessage } from 'element-plus'
import { computed, ref } from 'vue';
import $ from 'jquery';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
export default {
    name: "articleUploadView",
    components: {
        editorComponents,
    },
    provide() {
        return {
            'needContent': computed(() => this.needContent),
            'updataContent': computed(() => this.updataContent),
        }
    },
    setup() {
        let value = ref();
        let face = ref('');
        let title = ref("");
        let author = ref("");
        let content = ref("");
        let tag = ref("");
        let id = ref('');

        let fileList = ref([]);
        let tagList = ref(["新闻资讯", "精彩活动", "红色景点", "人物故事", "红色文化", "红色历史"]);

        let dialogVisible = ref(false);
        let needContent = ref(false);

        let cityChoose = ref('');
        let countyChoose = ref('');
        let city = ref(["南昌市", "九江市", "赣州市", "上饶市", "抚州市", "宜春市", "吉安市", "景德镇市", "萍乡市", "新余市", "鹰潭市"])
        let county = ref([]);

        const store = useStore();
        const router = useRouter();
        const route = useRoute();

        let isUpdata = ref(false);

        let updataContent = ref("");
        if (route.query.id != null) {
            //是否是别人的文章
            if (route.query.from == "checked") {
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/articleGet/isMyArticle/",
                    headers: {
                        "satoken": store.state.admin.token,
                    },
                    data: {
                        id: route.query.id,
                        author: store.state.admin.adminName,
                    },
                    cache: false,
                    async: false,
                    success(resp) {
                        if (resp == "error") {
                            const open4 = () => {
                                ElMessage.error('不能修改他人文章');
                            }
                            open4();
                            router.push({ name: "homeSetting" });
                            return;
                        }
                    }
                })
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/articleGet/getArticle/",
                    data: {
                        id: route.query.id,
                    },
                    success(resp) {
                        let t = JSON.parse(resp);
                        id.value = t.id;
                        face.value = t.face;
                        title.value = t.title;
                        author.value = t.author;
                        content.value = t.content;
                        updataContent.value = t.content;
                        tag.value = t.tag;
                        fileList.value.push({ uid: 0, url: t.face, name: "当前图片" });
                        isUpdata.value = true;
                        if (tag.value == "红色景点") {
                            $.ajax({
                                type: "post",
                                url: "http://124.221.73.180:3001/address/getAddress/",
                                headers: {
                                    "satoken": store.state.admin.token,
                                },
                                data: {
                                    aid: t.id,
                                },
                                cache: false,
                                async: false,
                                success(resp) {
                                    if (resp.slice(0, 1) == '景') {
                                        cityChoose.value = '景德镇市';
                                        handleChange();
                                        countyChoose.value = resp.slice(4);
                                    } else {
                                        cityChoose.value = resp.slice(0, 3);
                                        handleChange();
                                        countyChoose.value = resp.slice(3);
                                    }
                                    check.value = true;
                                }
                            })
                        }
                    }
                });
            } else if (route.query.from == "uncheck") {
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/getAuthor/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        id: route.query.id,
                    },
                    success(resp) {
                        if (resp == store.state.admin.adminName) {
                            const open4 = () => {
                                ElMessage.error('不能修改他人文章');
                            }
                            open4();
                            router.push({ name: "homeSetting" });
                            return;
                        }
                    }
                })
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/check/getArticle/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        id: route.query.id,
                    },
                    success(resp) {
                        let t = JSON.parse(resp);
                        id.value = t.id;
                        face.value = t.face;
                        title.value = t.title;
                        author.value = t.author;
                        content.value = t.content;
                        updataContent.value = t.content;
                        tag.value = t.tag;
                        fileList.value.push({ uid: 0, url: t.face, name: "当前图片" });
                        isUpdata.value = true;
                        if (t.tag == "红色景点") {
                            if (t.address.slice(0, 1) == '景') {
                                cityChoose.value = '景德镇市';
                                handleChange();
                                countyChoose.value = t.address.slice(4);
                            } else {
                                cityChoose.value = t.address.slice(0, 3);
                                handleChange();
                                countyChoose.value = t.address.slice(3);
                            }
                        }
                    }
                })
            }
        }
        let uploadFile = () => {//文件上传
            if (fileList.value.length != 1) {
                fileList.value[0] = fileList.value[1];
                fileList.value.splice(1, 1);
            }
            let file = ref(fileList.value[0]);
            var formData = new FormData();
            formData.append("image", file.value.raw);
            $.ajax({
                type: "post",
                url: "http://124.221.73.180:3001/upload/face/",
                headers: {
                    satoken: store.state.admin.token,
                },
                data: formData,
                contentType: false,
                processData: false,
                cache: false,
                async: false,
                success(resp) {
                    console.log("url是" + resp);
                    face.value = resp;
                }, error() {
                    const open4 = () => {
                        ElMessage({
                            showClose: true,
                            message: '上传图片过大',
                            type: 'error',
                        })
                    }
                    open4();
                    fileList.value.splice(1, 1);
                }
            })
        }

        let refeshContent = (i) => {
            content.value = i;
        }
        const options = ({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        let check = ref(false);
        let handleChange = () => {
            switch (cityChoose.value) {
                case '南昌市':
                    county.value = ["东湖区", "西湖区", "青云谱区", "青山湖区", "湾里区", "新建区", "南昌县", "进贤县", "安义县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "九江市":
                    county.value = ["浔阳区", "濂溪区", "柴桑区", '瑞昌市', "共青城市", "庐山市", "修水县", "武宁县", '永修县', "德安县", "都昌县", "湖口县", "彭泽县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "赣州市":
                    county.value = ["赣县区", "章贡区", "南康区", "龙南市", "瑞金市", "信丰县", "大余县", "上犹县", "崇义县", "安远县", "龙南县", "定南县", "全南县", "宁都县", "于都县", "会昌县", "寻乌县", "兴国县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "上饶市":
                    county.value = ["信州区", "广信区", "广丰区", "玉山县", "铅山县", "横峰县", "弋阳县", "余干县", "鄱阳县", "万年县", "婺源县", "德兴市"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "抚州市":
                    county.value = ["临川区", "东乡区", "南城县", "南丰县", "崇仁县", '乐安县', '金溪县', "黎川县", "宜黄县", "资溪县", "广昌县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "宜春市":
                    county.value = ["袁州区", "丰城市", '樟树市', "高安市", "奉新县", "万载县", "上高县", "宜丰县", '靖安县', "铜鼓县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "吉安市":
                    county.value = ["吉州区", "青原区", "井冈山市", "吉安县", "泰和县", "万安县", "遂川县", "永新县", "永丰县", "吉水县", "峡江县", "安福县", "新干县"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "萍乡市":
                    county.value = ["安源区", "湘东区", "芦溪县", "上栗县", "莲花县",];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "新余市":
                    county.value = ["分宜县", "渝水区"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "鹰潭市":
                    county.value = ["贵溪市", "余江区", "月湖区"];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
                case "景德镇市":
                    county.value = ["昌江区", "珠山区", "浮梁县", '乐平市'];
                    check.value = false;
                    check.value = true;
                    countyChoose.value = '';
                    break;
            }
        }
        let address = computed(() => { return cityChoose.value + countyChoose.value });
        let handleCommit = () => {
            if (tag.value == "") {
                const open4 = () => {
                    ElMessage.error('提交失败！请选择一个分类再提交文章');
                }
                open4();
                return;
            } else if (title.value == "") {
                const open4 = () => {
                    ElMessage.error('提交失败！请填写文章标题');
                }
                open4();
                return;
            } else if (tag.value == "红色景点" && address.value == "") {
                const open4 = () => {
                    ElMessage.error('提交失败！请选择地址再提交文章');
                }
                open4();
                return;
            }
            let article = ref({
                id: id.value,
                title: title.value,
                face: face.value,
                content: content.value,
                author: store.state.admin.adminName,
                tag: tag.value,
            })
            const loadingInstance = ElLoading.service(options)
            if (route.query.id == null) {//不是上传
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/article/addCheck/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        article: JSON.stringify(article.value),
                        address: address.value,
                    },
                    cache: false,
                    async: false,
                    success() {
                        setTimeout(() => {
                            loadingInstance.close();
                            router.push({ name: 'adminUnCheck' });
                        }, 2000);
                    }
                })
            } else if (route.query.from == "checked") {//更新文章，先删除，然后加到审核数据库里
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/article/detele/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        id: id.value,
                    },
                    cache: false,
                    async: false,
                    success(resp) {
                        console.log(resp);
                    }
                })
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/article/addCheck/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        article: JSON.stringify(article.value),
                        address: address.value,
                    },
                    cache: false,
                    async: false,
                    success() {
                        setTimeout(() => {
                            loadingInstance.close();
                            router.push({ name: 'checkArticle' });
                        }, 2000);
                    }
                })
            } else if (route.query.from == "uncheck") {
                $.ajax({
                    type: "post",
                    url: "http://124.221.73.180:3001/updataArticle/",
                    headers: {
                        satoken: store.state.admin.token,
                    },
                    data: {
                        article: JSON.stringify(article.value),
                        address: address.value,
                    },
                    success() {
                        setTimeout(() => {
                            loadingInstance.close();
                            router.push({ name: 'checkArticle' });
                        }, 2000);
                    }
                })
            }
        }


        return {
            uploadFile,
            handleCommit,
            refeshContent,
            handleChange,

            router,
            check,
            city,
            county,
            address,
            cityChoose,
            countyChoose,

            dialogVisible,
            needContent,
            updataContent,

            tagList,
            fileList,
            face,
            title,
            author,
            tag,
            value,
        }
    }
}

</script>

<style scoped></style>